<template>
  <a-layout>
    <a-layout>
      <a-layout style="padding: 0 24px">
        <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
          <a-row>
            <a-col :span="8">
              <a-input v-model:value="searchObj.name" size="middle" placeholder="查询名称"/>
            </a-col>
            <a-col :span="8">
              <a-button size="middle" type="primary" @click="handlerSearch">查询</a-button>
              <a-button size="middle" type="primary" @click="handlerAdd">新增</a-button>
            </a-col>
          </a-row>

          <a-table :columns="columns"
                   :rowKey="record => record.id"
                   :data-source="ebooks"
                   :loading="loading"
                   :pagination="false">
            <template #cover="cover">
              <a-image
                  :width="50"
                  :height="50"
                  :src="cover.text"/>
            </template>
            <template v-slot:categories="{text,record}">
              {{ getCategoryName(record.category, record.secondary) }}
            </template>
            <template v-slot:action="{text,record}">
              <router-link :to="'/admin/doc?ebookId=' + record.id">
                <a-button size="middle" type="ghost">文档管理</a-button>
              </router-link>
              <a-button size="middle" type="primary" @click="handlerEdit(record)">编辑</a-button>
              <a-button size="middle" :danger="true" @click="handlerRemove(record.id)">删除</a-button>
            </template>
          </a-table>
          <mine-pagination :current="current" :size="size" :total="total"
                           @init-table-data="handlerPageChangerQuery"></mine-pagination>
        </a-layout-content>
      </a-layout>
    </a-layout>
  </a-layout>

  <a-modal
      v-model:visible="modalVisible"
      :confirm-loading="modalConfirmLoading"
      title="电子书列表"
      @ok="handlerModalOk">
    <a-form :model="formEbook" :label-col="formLabelCol" :wrapper-col="formWrapperCol">
      <a-form-item label="封面">
        <a-input v-model:value="formEbook.cover"/>
      </a-form-item>
      <a-form-item label="名称">
        <a-input v-model:value="formEbook.name"/>
      </a-form-item>
      <a-form-item label="分类">
        <!--        <a-input v-model:value="formEbook.categories"/>-->
        <a-cascader v-model:value="formEbook.categories"
                    :field-names="{ label: 'name', value: 'id', children: 'children' }"
                    :options="categories"
                    placeholder="Please select"/>
      </a-form-item>
      <a-form-item label="描述">
        <a-input v-model:value="formEbook.description"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import * as ebook from '@/api/wiki/ebook'
import {onMounted, ref} from "vue";
import MinePagination from "../../components/mine-pagination";
import {message, Modal} from "ant-design-vue";

export default {
  name: "Ebook",
  components: {MinePagination},
  setup() {
    const current = ref(1)
    const size = ref(10)
    const total = ref(5)
    const ebooks = ref([])
    const searchObj = ref({})
    const loading = ref(true)
    const columns = ref([{
      title: '封面',
      dataIndex: 'cover',
      slots: {customRender: 'cover'}
    }, {
      title: '名称',
      dataIndex: 'name',
    }, {
      title: '分类',
      key: 'categories',
      dataIndex: 'categories',
      slots: {customRender: 'categories'}
    }, {
      title: '文档数',
      dataIndex: 'docCount',
    }, {
      title: '阅读数',
      dataIndex: 'viewCount',
    }, {
      title: '点赞数',
      dataIndex: 'voteCount',
    }, {
      title: '操作',
      dataIndex: 'action',
      slots: {customRender: 'action'}
    }])
    //对话框是否可见
    const modalVisible = ref(false)
    //确定按钮 loading
    const modalConfirmLoading = ref(false)
    const formEbook = ref({})
    const formLabelCol = ref({span: 4})
    const formWrapperCol = ref({span: 14})
    const categories = ref([{}])


    const handlerQueryInit = (params) => {
      if (!params) {
        params = {
          current: current.value,
          size: size.value,
        }
      }
      ebook.wikis(params).then(res => {
        loading.value = false
        let result = res.data
        ebooks.value = result.records
        current.value = result.current
        size.value = result.size
        total.value = result.total
      });
    }

    const handlerQueryCategories = () => {
      ebook.categories().then(res => {
        if (res.success) {
          categories.value = res.data[0].children
        } else {
          message.error(res.msg);
        }
      })
    }

    const handlerSearch = () => {
      searchObj.value.current = current.value
      searchObj.value.size = size.value
      handlerQueryInit(searchObj.value)
    }
    const handlerPageChangerQuery = (params) => {
      handlerQueryInit(params)
    }
    const handlerEdit = (record) => {
      modalVisible.value = true
      formEbook.value = JSON.parse(JSON.stringify(record))
      formEbook.value.categories = [record.category, record.secondary]
    }
    const handlerAdd = () => {
      modalVisible.value = true
      formEbook.value = {}
    }
    const handlerRemove = (id) => {
      Modal.confirm({
        title: '删除',
        content: '确定要删除这些数据吗?',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          ebook.remove(id).then(res => {
            if (res.status === 200) {
              message.success(res.msg);
              handlerQueryInit()
            } else {
              message.error(res.msg);
            }
          })
        },
        onCancel() {
        }
      })
    }

    const handlerModalOk = () => {
      modalConfirmLoading.value = true
      if (formEbook.value.categories) {
        let categories = formEbook.value.categories
        formEbook.value.category = categories[0]
        formEbook.value.secondary = categories[1]
      }
      if (formEbook.value.id) {
        ebook.update(formEbook.value).then(res => {
          modalVisible.value = false
          modalConfirmLoading.value = false
          if (res.status === 200) {
            message.success(res.msg);
            handlerQueryInit()
          } else {
            message.error(res.msg);
          }
        })
      } else {
        ebook.save(formEbook.value).then(res => {
          modalVisible.value = false
          modalConfirmLoading.value = false
          if (res.status === 200) {
            message.success(res.msg);
            handlerQueryInit()
          } else {
            message.error(res.msg);
          }
        })
      }
    }

    const getCategoryName = (categoryId, secondaryId) => {
      if (!categoryId) {
        return
      }
      let categoryName = ''
      let secondaryName = ''
      categories.value.forEach((item) => {
        if (item.id === categoryId) {
          categoryName = item.name
          item.children.forEach((item) => {
            if (item.id === secondaryId) {
              secondaryName = item.name
            }
          })
        }
      })
      return `${categoryName}/${secondaryName}`
    }

    onMounted(() => {
      handlerQueryInit()
      handlerQueryCategories()
    })

    return {
      // 表格
      ebooks,
      loading,
      columns,
      //搜索
      searchObj,
      //分页
      current,
      size,
      total,
      //对话框
      modalVisible,
      modalConfirmLoading,
      //form表单
      formEbook,
      formLabelCol,
      formWrapperCol,
      categories,

      //初始化表格数据
      handlerQuery: handlerQueryInit,
      //搜索
      handlerSearch,
      //切换分页
      handlerPageChangerQuery,
      //编辑
      handlerEdit,
      //新增
      handlerAdd,
      //删除
      handlerRemove,
      //提交表单
      handlerModalOk,
      getCategoryName
    }

  }
}
</script>

<style scoped>

</style>
